<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './index.data';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import aes from '@/utils/aes';
  import { getMenuList } from '@/api/sys/menu';

  import { useMessage } from '@/hooks/web/useMessage';

  import { savedata } from '@/api/removeWatermark/removeWatermark';

  defineOptions({ name: 'Modal' });

  const { createMessage: msg } = useMessage();

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, setProps }] = useForm(
    {
      labelWidth: 140,
      schemas: formSchema,
      showActionButtonGroup: false,
      baseColProps: { lg: 12, md: 24 },
    },
  );

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setProps({ disabled: data.isLook });
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
    // const treeData = await getMenuList();
    // updateSchema({
    //   field: 'parentId',
    //   componentProps: { treeData },
    // });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      const res = await savedata(values);
      if (res.isSucceed) {
        msg.success('操作成功');
        closeModal();
        emit('success');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
